/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.knet.sp.ncrm.modules.sys.region.web;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import cn.knet.sp.ncrm.common.beanvalidator.BeanValidators;
import cn.knet.sp.ncrm.common.config.Global;
import cn.knet.sp.ncrm.common.persistence.AjaxMessage;
import cn.knet.sp.ncrm.common.persistence.Page;
import cn.knet.sp.ncrm.common.utils.StringUtils;
import cn.knet.sp.ncrm.common.web.BaseController;
import cn.knet.sp.ncrm.modules.sys.region.entity.Region;
import cn.knet.sp.ncrm.modules.sys.region.service.RegionService;
import cn.knet.sp.ncrm.modules.sys.utils.RegionUtils;

/**
 * 客户区域Controller
 * @author zhangbin
 * @version 2015-08-27
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/region")
public class RegionController extends BaseController {

	@Autowired
	private RegionService regionService;
	
	@ModelAttribute
	public Region get(@RequestParam(required=false) String id) {
		Region entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = regionService.get(id);
		}
		if (entity == null){
			entity = new Region();
		}
		return entity;
	}

	private void trim(Region region) {
		if(region!=null&&StringUtils.isNotBlank(region.getRegionName())){
			region.setRegionName(StringUtils.trim(region.getRegionName()));
		}
		if(region!=null&&StringUtils.isNotBlank(region.getNumber())){
			region.setNumber(StringUtils.trim(region.getNumber()));
		}
	}

	@RequiresPermissions("sys:region:view")
	@RequestMapping(value = {"list", ""})
	public String list(Region region, HttpServletRequest request, HttpServletResponse response, Model model) {
		return "modules/sys/region/regionAjaxList";//ajax模式
	}

	@RequiresPermissions("sys:region:view")
	@RequestMapping(value = "listAjaxData")
	@ResponseBody
	public Page listAjaxData(Region region, HttpServletRequest request, HttpServletResponse response, Model model) {
		region.setUserType("1");
		Page<Region> page = new Page<Region>(request, response);
//		page.setOrderBy("to_char(sort_order,'000') asc");
		page.setOrderBy("sort_order asc");
		page = regionService.findPage(page, region);
		return page;
	}

	@RequiresPermissions("sys:region:view")
	@RequestMapping(value = "form")
	public String form(Region region, Model model) {
	    region.addHistoryFlag();
		model.addAttribute("region", region);
		return "modules/sys/region/regionForm";
	}

	@RequiresPermissions("sys:region:edit")
	@RequestMapping(value = "save")
	public String save(Region region, Model model, RedirectAttributes redirectAttributes) {
		this.trim(region);
		region.setUserType("1");
		region.setParentId("0");
		if (!beanValidator(model, region)){
			return form(region, model);
		}
		String name = region.getRegionName();
		if(name.endsWith("市") || name.endsWith("省")){ //以防万一特殊处理 此处name不为空
			addMessage(model, "不要以XX市或XX省结尾系统的固定区域已经包含这些数据!");
			return form(region, model);
		}

		if(region.getIsNewRecord()){
			region.setDateCreated(new java.util.Date());
		}
		int count = regionService.findDistinctRegion(region);
		if(count>0){
			addMessage(model, "区域["+region.getRegionName()+"]已经存在,请更换名称");
			return form(region, model);
		}
		count = regionService.findChina(region);
		if(count>0){
			addMessage(model, "区域["+region.getRegionName()+"]已经在固定区域存在,请更换名称");
			return form(region, model);
		}
		region.setLastUpdated(new java.util.Date());
		regionService.save(region);
		RegionUtils.clearRegion(region);
		addMessage(redirectAttributes, "保存客户区域成功");
		return "redirect:"+Global.getAdminPath()+"/sys/region/?repage";
	}

	@RequiresPermissions("sys:region:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public Object delete(Region region, RedirectAttributes redirectAttributes) {
		AjaxMessage result = AjaxMessage.success();
		try {
			regionService.delete(region);
			RegionUtils.clearRegion(region);
			result.appendMessage("删除客户区域成功!");
		} catch (Exception e) {
			logger.warn("删除客户区域失败", e);
			result.makeError("删除客户区域失败!系统发生异常");
		}
		return result;
	}

	/****************************
	 * 固定区域片段
	 ****************************/

	@RequiresPermissions("sys:region:view")
	@RequestMapping(value = "listAdmin")
	public String listAdmin(Region region, HttpServletRequest request, HttpServletResponse response, Model model) {
		return "modules/sys/region/regionAdminAjaxList";//ajax模式
	}

	@RequiresPermissions("sys:region:view")
	@RequestMapping(value = "listAdminAjaxData")
	@ResponseBody
	public Object listAdminAjaxData(Region region, HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxMessage result = AjaxMessage.success();
		region.setUserType("0");//设置默认的类型
		if(region==null||StringUtils.isBlank(region.getParentId())){
			region.setParentId("-1");
		}
		try {
			List<Region> list = regionService.findAdminList(region); //查询时直接将子节点下一级查询出来
			result.put("list",list);
		} catch (Exception e) {
			logger.warn("查询区域发生异常",e);
			result.makeError("查询区域发生异常");
		}
		return result;
	}

	@RequiresPermissions("sys:region:edit")
	@RequestMapping(value = "saveAdmin")
	@ResponseBody
	public Object saveAdmin(Region region) {
		AjaxMessage result = AjaxMessage.success();
		this.trim(region);
		region.setSortOrder("255");
		try{
			BeanValidators.validateWithException(validator, region);
			if(region.getIsNewRecord()){
				region.setDateCreated(new java.util.Date());
				region.setRegionLevel(String.valueOf(Integer.valueOf(region.getRegionLevel()) + 1));
				//新数据级别加1
			}

			if(StringUtils.isNotBlank(region.getNumber())){
				if("0".equals(region.getNumber())){
					result.makeError("固定区域编号[0]严格禁止使用!请更换编号");
					return result;
				}
				if("3687".equals(region.getNumber())){
					result.makeError("固定区域编号[3687]严格禁止使用!3687编号不能被编辑");
					return result;
				}

				Region oldRege = regionService.get(region.getNumber());
				if(oldRege!=null){
					if(!oldRege.getId().equals(region.getId())){ //两条记录不等
						result.makeError("固定区域编号["+region.getNumber()+"]已经存在,请更换编号");
						return result;
					}
				}
			}
			int count = regionService.findDistinctRegion(region);
			if(count>0){
				result.makeError("固定区域["+region.getRegionName()+"]已经存在,请更换名称");
				return result;
			}
			region.setLastUpdated(new java.util.Date());//必加修改时间
			regionService.saveAdmin(region);
			RegionUtils.clearRegion(region);
			result.setMessage("保存固定区域成功");
		} catch(ConstraintViolationException ex){
			List<String> list = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
			list.add(0, "数据验证失败：");
			result.makeError(list.toArray(new String[]{}).toString());
		} catch (Exception e){
			result.makeError("保存固定区域发生异常");
		}
		return result;
	}
}